33. Exercise: Sunshine Notifications
Fill out NotificationUtils
We’ve started this for you, as there is some code that simply has nothing to do with creating notifications, and rather just accessing our data. We wanted you to get right into it, so let's do just that.
- (1) Create a constant int identifier for our notification. This can be used later to access the notification. Very useful for updates and for cancelling ongoing notifications, things like that.
- (2) Next, create an Intent with the proper Uri to start the
DetailActivity. - (3) We want to navigate back to the
MainActivityfrom theDetailActivityif the user clicks the Notification and then clicks back, so useTaskStackBuilderfor that. - (4) Finally, assign that intent to the
NotificationBuilderobject so that when the user clicks the notification, it is fired off. - (5) In order to notify the user, we need a reference to the
NotificationManager, so usegetSystemServiceto do so. - (6) Now that everything is ready, notify the user and also save the time at which we showed this notification. Notifications are totally super awesome, but we don’t want to annoy our users with too many of them.
Bools and default values
We’ll have a preference for whether or not to show notifications. The default value for this preference will be true, but we don’t want to just hard code that value.
- Create
bools.xmlunderres/valuesand within it, create a boolean value set totrue.
Should we notify the user when we sync the data?
Using FirebaseJobDispatcher, we plan on updating the data from 6 to 8 times a day, depending on exactly when the system decides that’s best. We don’t want to send the user that many notifications, though!
- Within
SunshineSyncTask, first check to see if notifications are enabled at all. If they are, we’ll also need to check to see when the last time we notified the user was. If it was less than a day ago, it’s better that we hold off, and just keep our user happy that her weather data is up to date and ready to be displayed as soon as she wants it!
** Android O **
The launch of Android O might cause some functionality in the solution code to not work as expected. Unfortunately Sunshine from this point onward will not be maintained.
Exercise: Sunshine Notifications
SOLUTION:
- Fill out the NotifyUserOfNewWeather method
- Call NotifyUserOfNewWeather from syncWeather in SunshineSyncTask